package com.example.myweb.Service.Auth.Impl;

import com.example.myweb.Domain.Entity.Like;
import com.example.myweb.Domain.Entity.User;
import com.example.myweb.Domain.Entity.Like.LikeTargetType;
import com.example.myweb.Exception.CustomException;
import com.example.myweb.Repository.JpaRepository.ArticleRepository;
import com.example.myweb.Repository.JpaRepository.CommentRepository;
import com.example.myweb.Repository.JpaRepository.DynamicRepository;
import com.example.myweb.Repository.JpaRepository.LikeRepository;
import com.example.myweb.Service.Auth.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
//
@Service
public class LikeServiceImpl implements LikeService {

    @Autowired
    private LikeRepository likeRepository;
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private DynamicRepository dynamicRepository;
    @Autowired
    private CommentRepository commentRepository;

    @Override
    @Transactional
    public void likeTarget(String targetTypeStr, Long targetId, User currentUser) {
        Like.LikeTargetType targetType = parseAndValidateType(targetTypeStr);

        // 1. 检查目标是否存在
        validateTargetExists(targetType, targetId);

        // 2. 检查是否已点赞
        if (likeRepository.existsByUserAndTargetTypeAndTargetId(currentUser, targetType, targetId)) {
            return; // 幂等性：重复点赞不做任何事
        }

        // 3. 创建点赞记录
        Like newLike = new Like();
        newLike.setUser(currentUser);
        newLike.setTargetType(targetType);
        newLike.setTargetId(targetId);
        likeRepository.save(newLike);

        // 4. 更新目标的点赞数
        updateLikeCount(targetType, targetId, 1);
    }

    @Override
    @Transactional
    public void unlikeTarget(String targetTypeStr, Long targetId, User currentUser) {
        Like.LikeTargetType targetType = parseAndValidateType(targetTypeStr);

        // 直接尝试删除，并获取删除的记录数
        long deletedCount = likeRepository.deleteByUserAndTargetTypeAndTargetId(currentUser, targetType, targetId);

        // 如果确实删除了记录，才更新计数器
        if (deletedCount > 0) {
            updateLikeCount(targetType, targetId, -1);
        }
    }

    /**
     * 辅助方法：检查点赞的目标是否存在
     */
    private void validateTargetExists(Like.LikeTargetType targetType, Long targetId) {
        boolean exists = switch (targetType) {
            case ARTICLE -> articleRepository.existsById(targetId);
            case DYNAMIC -> dynamicRepository.existsById(targetId);
            // === 新增对COMMENT类型的处理 ===
            case COMMENT -> commentRepository.existsById(targetId);
        };
        if (!exists) {
            throw new CustomException("点赞目标不存在", HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 辅助方法：更新目标的点赞计数器
     */
    private void updateLikeCount(Like.LikeTargetType targetType, Long targetId, int delta) {
        switch (targetType) {
            case ARTICLE -> articleRepository.findById(targetId).ifPresent(article -> {
                article.setLikeCount(Math.max(0, article.getLikeCount() + delta));
                articleRepository.save(article);
            });
            case DYNAMIC -> dynamicRepository.findById(targetId).ifPresent(dynamic -> {
                dynamic.setLikeCount(Math.max(0, dynamic.getLikeCount() + delta));
                dynamicRepository.save(dynamic);
            });
            // === 新增对COMMENT类型的处理 ===
            case COMMENT -> commentRepository.findById(targetId).ifPresent(comment -> {
                comment.setLikeCount(Math.max(0, comment.getLikeCount() + delta));
                commentRepository.save(comment);
            });
        }
    }

    private Like.LikeTargetType parseAndValidateType(String typeStr) {
        try {
            return Like.LikeTargetType.valueOf(typeStr.toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new CustomException("不支持的点赞目标类型: " + typeStr, HttpStatus.BAD_REQUEST);
        }
    }

//    private void validateTargetExists(Like.LikeTargetType targetType, Long targetId) {
//        boolean exists = switch (targetType) {
//            case ARTICLE -> articleRepository.existsById(targetId);
//            case DYNAMIC -> dynamicRepository.existsById(targetId);
//            case COMMENT -> throw new UnsupportedOperationException("评论点赞暂未实现");
//        };
//        if (!exists) {
//            throw new CustomException("点赞目标不存在", HttpStatus.NOT_FOUND);
//        }
//    }
//
//    private void updateLikeCount(Like.LikeTargetType targetType, Long targetId, int delta) {
//        switch (targetType) {
//            case ARTICLE -> articleRepository.findById(targetId).ifPresent(article -> {
//                article.setLikeCount(article.getLikeCount() + delta);
//                articleRepository.save(article);
//            });
//            case DYNAMIC -> dynamicRepository.findById(targetId).ifPresent(dynamic -> {
//                dynamic.setLikeCount(dynamic.getLikeCount() + delta);
//                dynamicRepository.save(dynamic);
//            });
//            case COMMENT -> { /* 未来在这里实现更新评论的点赞数 */ }
//        }
//    }
}
//@Service
//public class LikeServiceImpl implements LikeService {
//
//    @Autowired
//    private LikeRepository likeRepository;
//    @Autowired
//    private ArticleRepository articleRepository;
//
//    @Override
//    @Transactional
//    public void likeTarget(String targetType, Long targetId, User currentUser) {
//        // === 修改这里的转换方式 ===
//        LikeTargetType typeEnum;
//        try {
//            // 使用 Enum.valueOf() 进行转换，它会自动处理大小写（需要先转大写）
//            typeEnum = LikeTargetType.valueOf(targetType.toUpperCase());
//        } catch (IllegalArgumentException e) {
//            throw new CustomException("不支持的点赞目标类型: " + targetType, HttpStatus.BAD_REQUEST);
//        }
//
//
//        // 1. 检查目标是否存在
//        validateTargetExists(typeEnum, targetId); // 让辅助方法也使用枚举
//
//        // 2. 检查是否已点赞过
//        if (likeRepository.existsByUserAndTargetTypeAndTargetId(currentUser, typeEnum, targetId)) {
//            return;
//        }
//
//        // 3. 创建新的点赞记录
//        Like newLike = new Like();
//        newLike.setUser(currentUser);
//        newLike.setTargetType(typeEnum); // <<< 这里现在是正确的类型了
//        newLike.setTargetId(targetId);
//        likeRepository.save(newLike);
//
//        // 4. 更新对应目标表中的 like_count 字段
//        updateLikeCount(typeEnum, targetId, 1);
//    }
//
//    @Override
//    @Transactional
//    public void unlikeTarget(String targetType, Long targetId, User currentUser) {
//        // === 同样修改这里的转换方式 ===
//        LikeTargetType typeEnum;
//        try {
//            typeEnum = LikeTargetType.valueOf(targetType.toUpperCase());
//        } catch (IllegalArgumentException e) {
//            throw new CustomException("不支持的点赞目标类型: " + targetType, HttpStatus.BAD_REQUEST);
//        }
//
//        // 1. 查找并删除点赞记录
//        long deletedCount = likeRepository.deleteByUserAndTargetTypeAndTargetId(currentUser, typeEnum, targetId);
//
//        // 2. 如果成功删除了记录，则更新对应目标的 like_count
//        if (deletedCount > 0) {
//            updateLikeCount(typeEnum, targetId, -1);
//        }
//    }
//
//    // === 修改辅助方法的参数类型 ===
//    private void validateTargetExists(LikeTargetType targetType, Long targetId) {
//        switch (targetType) {
//            case ARTICLE:
//                if (!articleRepository.existsById(targetId)) {
//                    throw new CustomException("要点赞的文章不存在", HttpStatus.NOT_FOUND);
//                }
//                break;
//            case DYNAMIC:
//                // if (!dynamicRepository.existsById(targetId)) { ... }
//                break;
//            case COMMENT:
//                // if (!commentRepository.existsById(targetId)) { ... }
//                break;
//        }
//    }
//
//    private void updateLikeCount(LikeTargetType targetType, Long targetId, int delta) {
//        switch (targetType) {
//            case ARTICLE:
//                articleRepository.findById(targetId).ifPresent(article -> {
//                    article.setLikeCount(article.getLikeCount() + delta);
//                    articleRepository.save(article);
//                });
//                break;
//            // ... 其他 case
//        }
//    }
//}